﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MobileSales.Website.Models;
using MobileSales.Model.Employees;
using MobileSales.Website.Properties;
using MobileSales.Common.Logger;
using MobileSales.Website.Localization;

namespace MobileSales.Website.Controllers
{
    public class AccountController : ControllerBase
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************
        
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                string token = MembershipService.ValidateUser(model.UserName, model.Password);
                if (token!=null)
                {
                    AuthService.AuthServiceClient clnt = new AuthService.AuthServiceClient();
                    bool hasWebAccess = clnt.TokenHasWebsiteAccess(token);
                    int employeeId = clnt.GetUserIdFromToken(token);
                    clnt.Close();

                    if (hasWebAccess)
                    {
                        FormsService.SignIn(model.UserName, model.RememberMe);
                        this.SaveTokenCookie(token, employeeId);

                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorStrings.ThisUserIsNotManager);
                    }
                }
                else
                {
                    ModelState.AddModelError("", ErrorStrings.IncorrectUserOrPassword);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }


        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            ClearTokenCookie();
            FormsService.SignOut();
            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        //public ActionResult Register()
        //{
        //    ViewModel.PasswordLength = MembershipService.MinPasswordLength;
        //    return View();
        //}

        //[HttpPost]
        //public ActionResult Register(Model.Employees.Employee model, int contractId, int roleId, FormCollection form)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        // Attempt to register the user
        //        model.Role = new Role { Id = roleId };
        //        model.Contract = new Contract { Id = roleId };
        //        model.Params = this.GetParameters(form, Model.Params.ParamType.Employee);
        //        MembershipCreateStatus createStatus = MembershipService.CreateUser(model);

        //        if (createStatus == MembershipCreateStatus.Success)
        //        {
        //            this.SetMessage("Account created successfully.\nPlease log in...", Infrastructure.Messaging.MessageType.Info);
        //            return RedirectToAction("Index", "Home");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    ViewModel.PasswordLength = MembershipService.MinPasswordLength;
        //    return View(model);
        //}

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewModel.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(this.Token, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", ErrorStrings.IncorrectUserOrPassword);
                }
            }

            // If we got this far, something failed, redisplay form
            ViewModel.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }


        #region Remind
        public ActionResult Remind()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Remind(string email, FormCollection form)
        {
            try
            {
                AuthService.AuthServiceClient cli = new AuthService.AuthServiceClient();
                cli.RemindPassword(email);
                cli.Close();
                this.SetMessage(InfoStrings.NewPasswordHasBeenSent, Infrastructure.Messaging.MessageType.Info);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                this.SetMessage(ErrorStrings.ErrorRemindPassword, Infrastructure.Messaging.MessageType.Error);
            }
            return RedirectToAction("LogOn");
        } 
        #endregion

    }
}
